﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Skyhook.Core.Xml
{
    static class XmlHelpers
    {
        static public void AddAttributeAndSetValue<T>(XmlNode node, string attrname, T attr, bool alwaysadd = false) where T : IConvertible
        {
            bool isnull = false;

            if (typeof(T).IsValueType == false)
            {
                if ((object)attr == null)
                {
                    isnull = true;
                }
            }
            else
            {
                isnull = attr.Equals(default(T));
            }

            if (alwaysadd)
            {
                node.Attributes.Append(node.OwnerDocument.CreateAttribute(attrname));
                node.Attributes[attrname].Value = attr.ToString().ToLower();
            }
            if (!alwaysadd && !isnull)
            {
                node.Attributes.Append(node.OwnerDocument.CreateAttribute(attrname));
                node.Attributes[attrname].Value = attr.ToString().ToLower();
            }
        }

        static public T GetAttributeValue<T>(XmlNode node, string attrname, T defaultvalue = default(T)) where T : IConvertible
        {
            T result = defaultvalue;
            if (node.Attributes[attrname] != null)
            {
                try
                {
                    result = (T)Convert.ChangeType(node.Attributes[attrname].Value, typeof(T));
                }
                catch
                {
                }
            }
            return result;
        }
    }
}
